package com.linsir.file.util;

import com.linsir.core.launch.constant.SymbolConstant;
import com.linsir.core.util.D;
import com.linsir.core.util.S;
import com.linsir.file.util.filter.FileTypeFilter;
import com.linsir.file.util.filter.StrAttackFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author ：linsir
 * @date ：Created in 2022/9/17 21:32
 * @description：本地存储
 * @modified By：
 * @version: 0.0.1
 */

@Slf4j
public class LocalFileUtil {



    private static String localUploadPath;


    public static  void  setLocalUploadPath(String localUploadPath)
    {
        LocalFileUtil.localUploadPath = localUploadPath;
    }

    /**
     * 上传本地服务器上
     * @param file
     * @return
     */
    public static String storage(MultipartFile file){
        String bizPath = D.getYear()+ File.separator+D.getYearMonth4() + File.separator+D.getDay();
        return storage(file,bizPath);
    }

    /**
     *
     * @param mf
     * @param bizPath  业务地址，
     * @return
     */
    public static String storage(MultipartFile mf, String bizPath){

        //update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        bizPath= StrAttackFilter.filter(bizPath);
        try {
            String ctxPath = localUploadPath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator );
            if (!file.exists()) {
                // 创建文件根目录
                file.mkdirs();
            }
            // 获取文件名
            String orgName = mf.getOriginalFilename();
            orgName = FileCommonUtils.getFileName(orgName);

            if(orgName.indexOf(SymbolConstant.SPOT)!=-1){
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
            }else{
                fileName = orgName+ "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileTypeFilter.fileTypeFilter(mf);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if(S.isNotEmpty(bizPath)){
                dbpath = bizPath + File.separator + fileName;
            }else{
                dbpath = fileName;
            }
            if (dbpath.contains(SymbolConstant.DOUBLE_BACKSLASH)) {
                dbpath = dbpath.replace(SymbolConstant.DOUBLE_BACKSLASH, SymbolConstant.SINGLE_SLASH);
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }
}
